package com.smh.yunpicturebackend.schedule;

import com.smh.yunpicturebackend.pojo.domain.Picture;
import com.smh.yunpicturebackend.service.PictureService;
import com.smh.yunpicturebackend.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shiminghui
 * @date 2025/6/23 10:59
 * @description: 定时任务
 */
@Slf4j
@Component
public class PictureSchedule {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Resource
    private AliyunOSSUtils aliyunOSSUtils;
    @Resource
    private PictureService pictureService;

    /**
     * 定时任务，每6个小时执行一次，删除所有过时的图片
     */
    @Scheduled(cron = "0 0 0/6 * * ? ")
    public void deleteExpiredPictures() {
        // 查询过期的图片
        List<Picture> expiredPictures = pictureService.lambdaQuery().eq(Picture::getIsDelete, 1).list();
        // 拿到所有的url地址
        List<String> allPictureUrls = pictureService.getAllPictureUrls(expiredPictures);

        // 删除图片
        Integer delectCount = aliyunOSSUtils.deleteFiles(allPictureUrls);
        log.info("时间:{},删除了{}张图片.", sdf.format(new Date()), delectCount);

        // 删除数据库记录
        List<Long> pictureIds = expiredPictures.stream().map(Picture::getId).collect(Collectors.toList());
        boolean b = pictureService.removeByIds(pictureIds, true); // 强制删除
        if (!b) {
            log.info("时间:{},删除了{}张图片,但数据库记录删除失败.", sdf.format(new Date()), delectCount);
        }
    }

}
